package cc.sunni.test.baidu;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * 图片识别的过程
 * 1.取样本
 * 2.清洗区分样本
 * 3.提取样本特征
 * 4.提取目标的特征与样本进行对比
 */
public class Baacloud {

    public static void main(String[] args) throws IOException {
        HttpResponse response = HttpRequest.get("https://www.baacloud11.com/other/captcha.php")
                .execute();
        byte[] imgData = response.bodyBytes();
        removeBackground(imgData);
        GeneralBasic.generalBasic(imgData);

    }

    /**
     * 根据颜色深浅与灰度值对比,将浅颜色置换成白色,深颜色置换成黑色
     * 通过颜色的深浅去除干扰因素
     * 通过灰度处理，将验证码中颜色较浅的点置换成白色，颜色较深的点置换成黑色。
     */
    public static BufferedImage removeBackground(byte[] imgData) throws IOException {
        int grayValue = 135;
        BufferedImage img = ImageIO.read(new ByteArrayInputStream(imgData));
        int width = img.getWidth();
        int height = img.getHeight();

        for (int x = 0; x < width; ++x) {
            for (int y = 0; y < height; ++y) {
                int p = img.getRGB(x, y);
                int a = (p >> 24) & 0xff;
                int r = (p >> 16) & 0xff;
                int g = (p >> 8) & 0xff;
                int b = p & 0xff;
                if (r * 0.299 + g * 0.578 + b * 0.114 >= grayValue) {
                    img.setRGB(x, y, Color.WHITE.getRGB());
                } else {
                    img.setRGB(x, y, Color.BLACK.getRGB());
                }
            }
        }
        return img;
    }

}
